package com.gitee.feizns.web.mvc.validate;

import com.gitee.feizns.ArrayUtils;
import com.gitee.feizns.web.mvc.validate.annotation.AllNotNull;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;
import java.util.Objects;

/**
 * @author feizns
 * @since 2019/7/24
 */
public class AllNotNullValidator implements ConstraintValidator<AllNotNull, Object> {

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        String msg = null;
        if ( value != null ) {
            boolean match = Arrays.stream(ArrayUtils.toArray(value)).anyMatch(Objects::isNull);
            if ( match )
                msg = "cannot contain null.";
        } else {
            msg = "cannot be null.";
        }

        if ( msg != null ) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(msg).addConstraintViolation();
            return false;
        }

        return true;
    }

}
